<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    style="margin-left:12px"
    :limit="1"
    :on-exceed="handleExceed"
    @change="onChange"
    :auto-upload="false"
    :show-file-list="false"
  >
    <template #trigger>
      <el-button type="primary">{{ props.name }}</el-button>
    </template>
    <!-- <el-button class="ml-3" type="success" @click="submitUpload">
      upload to server
    </el-button> -->
    <!-- <template #tip>
      <div class="el-upload__tip text-red">
        limit 1 file, new file will cover the old file
      </div>
    </template> -->
  </el-upload>
</template>

<script setup lang="ts">
import { ref , inject} from 'vue'
import { ElMessage, genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import createAxios from '/@/utils/axios';
import { cloneDeep, isEmpty } from 'lodash-es'
import type baTableClass from '/@/utils/baTable'
import { uuid } from '/@/utils/random'


const baTable = inject('baTable') as baTableClass


interface Props {
    type: 'image' | 'images' | 'file' | 'files'
    action:string
    name:string,
    // 上传请求时的额外携带数据
    data?: anyObj
    // 返回绝对路径
    returnFullUrl?: boolean
    // 可自定义el-upload的其他属性
    attr?: Partial<UploadProps>
}

const props = withDefaults(defineProps<Props>(), {
    type: 'file',
    action:'',
    name:'上传文件',
    data: () => {
        return {}
    },
    returnFullUrl: false,
    attr: () => {
        return {}
    },
})

const upload = ref<UploadInstance>()

const onChange = (file: any) => {
    if (!file || !file.raw) return
    let fd = new FormData()
    fd.append('file', file.raw!)
    fd = formDataAppend(fd)
    createAxios({
      url:'admin/'+ props.action,
      method:'POST',
      data:fd,
      params:{ uuid: uuid() }
    }).then(()=>{
      ElMessage.success('上传成功！')
      if(baTable) baTable.getIndex()
    })
}

const formDataAppend = (fd: FormData) => {
    if (props.data && !isEmpty(props.data)) {
        for (const key in props.data) {
            fd.append(key, props.data[key])
        }
    }
    return fd
}


const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}
</script>